package com.ai.http;

import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: MrHe
 * @create: 2023-11-21 23:59
 * @description:
 **/

public class HttpUtilTe {
    public static InputStream getStreamFromUrl(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // 检查响应码
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 获取输入流
            return connection.getInputStream();
        } else {
            // 处理错误响应或抛出异常
            throw new Exception("GET request failed with response code: " + responseCode);
        }
    }
}

// 使用方法
 class Main {
    public static void main(String[] args) {
        try {
            File file = new File("C:\\files\\dall3\\2\\loadCookie.png");
            InputStream stream = HttpUtilTe.getStreamFromUrl("https://oaidalleapiprodscus.blob.core.windows.net/private/org-Dz0nfvcnz6sFJuIOTJsKgLeS/user-GEgWGmXjIYsk89ssD35AFlN4/img-6YO3yVQZfqeaVJsQDYazSYLH.png?st=2023-11-21T14%3A53%3A10Z&se=2023-11-21T16%3A53%3A10Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-11-21T13%3A24%3A18Z&ske=2023-11-22T13%3A24%3A18Z&sks=b&skv=2021-08-06&sig=NwJSve2zlvZyIdKabCG/f1somkjnbmaTN2BSXsdc3zw%3D");
            // 读取流数据的逻辑
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            FileCopyUtils.copy(stream.readAllBytes(),file);

            // ...
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
